<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Db;

/**
 * 实名审核
 *
 * @icon fa fa-circle-o
 */
class Verify extends Backend
{
    
    /**
     * Verify模型对象
     * @var \app\admin\model\user\Verify
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Verify;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

        /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['checktime'] =time();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if($params['status'] ==2){
                        $verify_info['true_name']            = $row['true_name'];
                        $verify_info['id_card']              = $row['id_card'];
                        // $verify_info['id_card_hand_image']   = $row['id_card_hand_image'];
                        // $verify_info['id_card_front_image']  = $row['id_card_front_image'];
                        // $verify_info['id_card_behind_image'] = $row['id_card_behind_image'];
                        $findUser = Db::name('user')
                        ->where(['id'=>$row['user_id']])
                        ->find();
                        //累加上级直推人数
                        // $invite_user_id = Db::name('invite')->where('user_id',$row['user_id'])->value('invite_user_id');
                        // Db::name('user')
                        // ->where(['id'=>$invite_user_id])
                        // ->setInc('total_zt_person');
                        // //是否满足升级(直推人数/团队业绩)
                        // $invite_user = Db::name('user')
                        // ->where(['id'=>$invite_user_id])
                        // ->find();
                        // $findLevel = $invite_user['level']+1;
                        // $level = Db::name('user_level')
                        // ->where(['id'=>$findLevel])
                        // ->find();
                        // if(($invite_user['total_zt_person']>=$level['zhitui_number'])&&($invite_user['total_team_achievement']>=$level['team_performance'])){
                        //     Db::name('user')
                        //     ->where(['id'=>$invite_user_id])
                        //     ->setInc('level');
                        // }
                        //完成实名认证任务
                        $user_verifytask = Db::name('user_task')
                        ->where(['task_id'=>3,'user_id'=>$row['user_id']])
                        ->find();
                        if(!$user_verifytask){
                            $task_reward = Db::name('task')
                            ->where(['id'=>3])
                            ->value('task_reward');
                            if($task_reward){
                                Db::name('user')
                                ->where(['id'=>$row['user_id']])
                                ->update([
                                'mission_wallet' => Db::raw('mission_wallet+'.$task_reward),
                                'verify_status'  => 1,
                                'verify_info'    => json_encode($verify_info),
                                ]);
                                $user_balance_log['user_id']    = $row['user_id'];
                                $user_balance_log['amount']     = $task_reward;
                                $user_balance_log['before']     = $findUser['mission_wallet'];
                                $user_balance_log['after']      = $findUser['mission_wallet']+$task_reward;
                                $user_balance_log['remark']     = '完成实名认证任务';
                                $user_balance_log['type']       = 1;
                                $user_balance_log['log_type']   = 2;
                                $user_balance_log['source']     = 2;
                                $user_balance_log['task_id']    = 3;
                                $user_balance_log['createtime'] = time();
                                Db::name('user_balance_log')->insert($user_balance_log);
                                Db::name('user_task')->insert(['task_id'=>3,'user_id'=>$row['user_id'],'createtime'=>date('Y-m-d')]);
                            }
                            
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function multi($ids=null){
        $verifys  = Db::name('user_verify')
                    ->where('id','in',$ids)
                    ->where('status',0)
                    ->select();
        // $verifys = $this->model->get($ids);
        if (!$verifys) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);
                $checktime =time();
                Db::startTrans();
                try {
                    foreach ($verifys as $key => $value) {
                        if($params['params']==2)
                        {
                            $verify_info['true_name'] = $value['true_name'];
                            $verify_info['id_card'] = $value['id_card'];
                            Db::name('user')
                            ->where('id',$value['user_id'])
                            ->update(
                                ['verify_status'=>1,'verify_info'=>json_encode($verify_info)]
                            );

                            Db::name('user_verify')
                            ->where('id',$value['id'])
                            ->update(['status'=>2,'checktime'=>$checktime]);

                             //完成实名认证任务
                            $user_verifytask = Db::name('user_task')
                            ->where(['task_id'=>3,'user_id'=>$value['user_id']])
                            ->find();
                            if(!$user_verifytask){
                                $findUser = Db::name('user')
                                ->where(['id'=>$value['user_id']])
                                ->find();
                                $task_reward = Db::name('task')
                                ->where(['id'=>3])
                                ->value('task_reward');
                                if($task_reward){
                                    Db::name('user')
                                    ->where(['id'=>$value['user_id']])
                                    ->update([
                                    'mission_wallet' => Db::raw('mission_wallet+'.$task_reward),
                                    ]);
                                    $user_balance_log['user_id']    = $value['user_id'];
                                    $user_balance_log['amount']     = $task_reward;
                                    $user_balance_log['before']     = $findUser['mission_wallet'];
                                    $user_balance_log['after']      = $findUser['mission_wallet']+$task_reward;
                                    $user_balance_log['remark']     = '完成实名认证任务';
                                    $user_balance_log['type']       = 1;
                                    $user_balance_log['log_type']   = 2;
                                    $user_balance_log['source']     = 2;
                                    $user_balance_log['task_id']    = 3;
                                    $user_balance_log['createtime'] = time();
                                    Db::name('user_balance_log')->insert($user_balance_log);
                                    Db::name('user_task')->insert(['task_id'=>3,'user_id'=>$value['user_id'],'createtime'=>date('Y-m-d')]);
                                }
                                
                            }
                        }else{
                            Db::name('user_verify')
                            ->where('id',$value['id'])
                            ->update(['status'=>1,'checktime'=>$checktime]);
                        }
                    }
                    Db::commit();
                    $this->success();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
}
